package day06.concurrent03;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock的优势1：加锁 和 解锁可以在不同的 代码块/方法/类 中执行
 */
public class Demo03 {
    static String name = "小明";
    static String gender = "男";
    static boolean isDBOK = false;
    static Lock lock = new ReentrantLock();

    static void saveToDB(String name,String gender){
        if(isDBOK){
            System.out.println("########保存到数据库..");
        }else{
            //释放掉锁!
            lock.unlock();
            System.out.println("########重连数据库..需耗时1小时..");
            try {
                Thread.sleep(1000*60*60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.lock();
                    saveToDB(name,gender);
                    System.out.println(name+"#"+gender);
                    lock.unlock();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.lock();
                    if("小明".equals(name)){
                        name = "小花";
                        gender = "女";
                        System.out.println("########修改了信息！");
                    }else{
                        name = "小明";
                        gender = "男";
                        System.out.println("########修改了信息！");
                    }
                    lock.unlock();
                }
            }
        }).start();
    }
}
